import { mongodb } from '../config/mongodb';
import { ObjectId, Document } from 'mongodb';

// 集合名称常量
const COLLECTIONS = {
  QUESTION_CONTENTS: 'question_contents',
} as const;

// 问题内容数据结构
interface QuestionContent extends Document {
  _id?: ObjectId;
  content: string;
  attachments?: string[];
  createdAt: Date;
  updatedAt: Date;
}

export class QuestionContentService {
  /**
   * 创建问题内容
   * @param content 问题内容
   * @param attachments 附件列表
   * @returns MongoDB文档ID
   */
  static async createQuestionContent(
    content: string,
    attachments?: string[]
  ): Promise<string> {
    const contentCollection = mongodb.getCollection<QuestionContent>(
      COLLECTIONS.QUESTION_CONTENTS
    );

    const questionContent: QuestionContent = {
      content,
      attachments: attachments || [],
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await contentCollection.insertOne(questionContent);
    return result.insertedId.toString();
  }

  /**
   * 根据ID获取问题内容
   * @param contentId MongoDB文档ID
   * @returns 问题内容和附件
   */
  static async getQuestionContent(contentId: string): Promise<{
    content: string;
    attachments: string[];
  } | null> {
    try {
      const contentCollection = mongodb.getCollection<QuestionContent>(
        COLLECTIONS.QUESTION_CONTENTS
      );
      const questionContent = await contentCollection.findOne({
        _id: new ObjectId(contentId),
      });

      if (!questionContent) {
        return null;
      }

      return {
        content: questionContent.content,
        attachments: questionContent.attachments || [],
      };
    } catch (error) {
      console.error('Error fetching question content from MongoDB:', error);
      return null;
    }
  }

  /**
   * 更新问题内容
   * @param contentId MongoDB文档ID
   * @param content 新的内容（可选）
   * @param attachments 新的附件列表（可选）
   * @returns 是否更新成功
   */
  static async updateQuestionContent(
    contentId: string,
    content?: string,
    attachments?: string[]
  ): Promise<boolean> {
    try {
      const contentCollection = mongodb.getCollection<QuestionContent>(
        COLLECTIONS.QUESTION_CONTENTS
      );

      const updateData: Partial<QuestionContent> = {
        updatedAt: new Date(),
      };

      if (content !== undefined) {
        updateData.content = content;
      }

      if (attachments !== undefined) {
        updateData.attachments = attachments;
      }

      const result = await contentCollection.updateOne(
        { _id: new ObjectId(contentId) },
        { $set: updateData }
      );

      return result.modifiedCount > 0;
    } catch (error) {
      console.error('Error updating question content in MongoDB:', error);
      return false;
    }
  }

  /**
   * 删除问题内容
   * @param contentId MongoDB文档ID
   * @returns 是否删除成功
   */
  static async deleteQuestionContent(contentId: string): Promise<boolean> {
    try {
      const contentCollection = mongodb.getCollection<QuestionContent>(
        COLLECTIONS.QUESTION_CONTENTS
      );
      const result = await contentCollection.deleteOne({
        _id: new ObjectId(contentId),
      });
      return result.deletedCount > 0;
    } catch (error) {
      console.error('Error deleting question content from MongoDB:', error);
      return false;
    }
  }

  /**
   * 添加附件到现有问题内容
   * @param contentId MongoDB文档ID
   * @param attachment 新附件路径
   * @returns 是否添加成功
   */
  static async addAttachment(
    contentId: string,
    attachment: string
  ): Promise<boolean> {
    try {
      const contentCollection = mongodb.getCollection<QuestionContent>(
        COLLECTIONS.QUESTION_CONTENTS
      );

      const result = await contentCollection.updateOne(
        { _id: new ObjectId(contentId) },
        {
          $push: {
            attachments: attachment,
          } as any,
          $set: {
            updatedAt: new Date(),
          },
        }
      );

      return result.modifiedCount > 0;
    } catch (error) {
      console.error('Error adding attachment to question content:', error);
      return false;
    }
  }

  /**
   * 从问题内容中移除附件
   * @param contentId MongoDB文档ID
   * @param attachmentPath 要移除的附件路径
   * @returns 是否移除成功
   */
  static async removeAttachment(
    contentId: string,
    attachmentPath: string
  ): Promise<boolean> {
    try {
      const contentCollection = mongodb.getCollection<QuestionContent>(
        COLLECTIONS.QUESTION_CONTENTS
      );

      const result = await contentCollection.updateOne(
        { _id: new ObjectId(contentId) },
        {
          $pull: {
            attachments: attachmentPath,
          } as any,
          $set: {
            updatedAt: new Date(),
          },
        }
      );

      return result.modifiedCount > 0;
    } catch (error) {
      console.error('Error removing attachment from question content:', error);
      return false;
    }
  }
}
